package FileStudy;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

/**
 * 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件 (不包含目录)
 */
public class Fdemo10 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径:");
        String rootpath = scanner.next();
        System.out.println("请输入要查询的关键词:");
        String word = scanner.next();
        File rootDir = new File(rootpath);
        if (!rootDir.isDirectory()) {
            System.out.println("输入的路径非法！");
            return;
        }

        //2、递归的遍历
        scanDir(rootDir, word);
    }
    private static void scanDir(File rootDir,String word){
        File []files = rootDir.listFiles();
        if(files == null){
            return;
        }
        //2.遍历每个元素，针对普通文件和目录进行处理
        for (File f:files) {
            if(f.isFile()){
                //针对文件进行查找
                if(containsWord(f,word)){
                    try {
                        System.out.println(f.getCanonicalPath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }else if(f.isDirectory()){
                //针对目录进行递归
                scanDir(f,word);
            }
        }
    }

    private static boolean containsWord(File f,String word){
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)){
            while (true){
                char[] buffer = new char[1024];
                int len = reader.read(buffer);
                if(len == -1){
                    break;
                }
                //把这一段读到的结果，放到stringbuilder中、
                stringBuilder.append(buffer,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        //indexof返回子串的下标 如果word在stringbuilder中就返回true  否者返回false
        return stringBuilder.indexOf(word) != -1;
    }
}
